package com.example.yjj_java_web_homework3.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author Li Chun Hei
 * @date 4/11/2025
 * @description
 */
@Aspect
@Component
public class LoggingAspect {

    private static final Logger log = LoggerFactory.getLogger(LoggingAspect.class);

    @Pointcut("execution(* com.example.yjj_java_web_homework3.controller..*(..))")
    public void controllerMethods() {}

    @Around("controllerMethods()")
    public Object logControllerMethods(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getTarget().getClass().getSimpleName();

        log.info("开始执行: {}.{}()", className, methodName);

        long startTime = System.currentTimeMillis();
        Object result;
        try {
            result = joinPoint.proceed();
            long executionTime = System.currentTimeMillis() - startTime;
            log.info("执行完成: {}.{}() - 耗时: {}ms", className, methodName, executionTime);
            return result;
        } catch (Exception e) {
            log.error("执行异常: {}.{}() - 错误: {}", className, methodName, e.getMessage());
            throw e;
        }
    }
}
